package com.sjt.ForkJoinDemo;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
@Slf4j
public class CacheTest {

    public ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public static volatile Map<String, Object> map = new HashMap<>();

    public static CacheTest cache = new CacheTest();

    //存入缓存
    public void put(String key, Object value) {
        lock.writeLock().lock();
        try {
            log.debug(Thread.currentThread().getName() + " 正在写入：" + key);
            map.put(key, value);
            Thread.sleep(1);
            log.debug(Thread.currentThread().getName() + " 写入完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }
    //读取缓存
    public void get(String key, Object value) {
        lock.readLock().lock();
        try {
            log.debug(Thread.currentThread().getName() + " 正在读取：" + key);
            map.put(key, value);
            Thread.sleep(1);
            log.debug(Thread.currentThread().getName() + " 读取完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
    }

    public static void main(String[] args) {
      try {
          for (int i = 0; i < 10; i++) {
              int j = i;
              new Thread(() -> {
                  cache.put(String.valueOf(j), j + "1");
              }, "t" + i).start();
          }
          for (int i = 0; i < 10; i++) {
              final int j = i;
              new Thread(() -> {
                  cache.get(String.valueOf(j), j + "1");
              }, "t" + i).start();
          }
      }finally {
          map.clear();
      }

    }




}
